package com.google.code.memoriesalbum.controller.oauth;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.Logger;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slim3.controller.Controller;
import org.slim3.controller.Navigation;
import org.slim3.datastore.Datastore;
import org.slim3.datastore.EntityNotFoundRuntimeException;

import com.google.appengine.api.datastore.Key;
import com.google.code.memoriesalbum.model.Account;
import com.google.code.memoriesalbum.util.Constants;

/**
 * clientからの最後の確認を行うハンドラ。
 * @author shin1ogawa
 */
public class CompleteController extends Controller {

	static final Logger logger = Logger.getLogger(CompleteController.class.getName());


	@Override
	protected Navigation run() {
		if (StringUtils.isEmpty(asString("token"))) {
			response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
			response.addHeader(Constants.X_HEADER_ERRORMESSAGE, "ランダムトークンが設定されていません。");
		}
		Key key = Datastore.createKey(Account.class, asString("token"));
		try {
			Account account = Datastore.get(Account.class, key);
			account.setEnable(true);
			Datastore.put(account);
			response.setStatus(HttpServletResponse.SC_OK);
			response.setContentType("text/plain");
			response.setCharacterEncoding("utf-8");
			PrintWriter writer = response.getWriter();
			writer.println("id=" + account.getKey().getName());
			writer.println("token=" + account.getToken());
			writer.println("tokenSecret=" + account.getTokenSecret());
			response.flushBuffer();
			return null;
		} catch (EntityNotFoundRuntimeException e) {
			response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
			response.addHeader(Constants.X_HEADER_ERRORMESSAGE, "ランダムトークンが不正です。");
			return null;
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}
}
